#include "command.h"
/*
  BindCommand
    Bind a command & function relation to the list
  Argument
    list
      The list of command-function relations
    command
      The command string
    handle
      The function pointer to handle the command
  Return Value
    true
      Success
    false
      Failed
  BeginnerC
 */
bool BindCommand(CommandList *list, const char *command, int (*handle)(void *argument))
{
    Command *command_relation = NULL;
    if (NULL == list || NULL == command || NULL == handle)
    {
        return false;
    }
    command_relation = (Command*)calloc(1, sizeof(Command));
    if (NULL == command_relation)
    {
        return false;
    }
    strncpy(command_relation -> command, command, MAX_COMMAND_LENGTH);
    command_relation -> handle = handle;
    if (NULL == list -> first)
    {
        list -> first = command_relation;
        list -> last = command_relation;
    }
    else
    {
        list -> last -> next = command_relation;
        list -> last = command_relation;
    }
    return true;
}
/*
  InitList
    Init the list of command-function relations
  Argument
    No argument required
  Return Value
    If success, the function will return a pointer to the list.
    Else, the function will return NULL.
  BeginnerC
 */
CommandList* InitList()
{
    return (CommandList*)calloc(1, sizeof(CommandList));
}
/*
  FreeList
    Free the memory of the command-function list
  Argument
    list
      The list to the command-function
  Return Value
    No value will return
  BeginnerC
 */
void FreeList(CommandList* list)
{
    Command *relation = NULL, *temp = NULL;
    if (NULL == list)
    {
        return ;
    }
    relation = list -> first;
    temp = list -> first;
    while (temp)
    {
        temp = relation -> next;
        free(relation);
        relation = temp;
    }
    free(list);
    list = NULL;
}
/*
  HandleCommand
    Handle the command
  Argument
    list
      The list to the command-function
    command
      The command will be handle
    arguemnt
      The argument will give to the handle function
  Return Value
    The handle function's return value
    -1 Something wrong happend
  BeginnerC
 */
int HandleCommand(CommandList* list, const char *command, void *argument)
{
    Command *relation = NULL, *temp = NULL;
    if (NULL == list)
    {
        return -1;
    }
    relation = list -> first;
    temp = list -> first;
    while (temp)
    {
        temp = relation -> next;
        if (!strcmp(relation -> command, command))
        {
            return relation -> handle(argument);
        }
        relation = temp;
    }
    return -1;
}
